package com.xushu.controller;

import cn.hutool.core.collection.ListUtil;
import com.xushu.pojo.Customer;
import com.xushu.repositories.CustomerRepository;
import com.xushu.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;

@RestController
@RequestMapping("customer")
@Slf4j
public class CustomerController {

    @Autowired
    CustomerService service;
    @Autowired
    CustomerRepository customerRepository;

    @RequestMapping("add")
    public String batchAdd(){
        log.info("开始....");

        List<Customer> list=new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            list.add(new Customer("xushu"+i,"ShangHai"+i));
        }

        long begin = System.currentTimeMillis();
        customerRepository.saveAll(list);
        long end = System.currentTimeMillis();
        log.info("耗时:"+(end-begin));

        return "ok";
    }


    @RequestMapping("add2")
    public String batchAdd2(){
        log.info("开始....");

        List<Customer> list=new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            list.add(new Customer("xushu"+i,"ShangHai"+i));
        }

        List<List<Customer>> lists = ListUtil.partition(list, 10000);

        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        long begin = System.currentTimeMillis();
        for (List<Customer> listC : lists) {
            service.saveAll(listC,countDownLatch);
        }
        try {
            //保证之前的所有的线程都执行完成，才会走下面的；
            countDownLatch.await();
        } catch (Exception e) {
            log.error("阻塞异常:"+e.getMessage());
        }
        long end = System.currentTimeMillis();
        log.info("耗时:"+(end-begin));

        return "ok";
    }




    @RequestMapping("add3")
    public String batchAdd3(){
        log.info("开始....");

        long begin = System.currentTimeMillis();
        customerRepository.save(new Customer("xushu","ShangHai"));
        long end = System.currentTimeMillis();
        log.info("耗时:"+(end-begin));

        return "ok";
    }
}
